<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="流程标题" prop="noticeTitle">
        <el-input
            v-model="queryParams.noticeTitle"
            placeholder="请输入流程标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="流程序号" align="center" prop="taskDefinitionKey" width="180" />
      <el-table-column label="流程标题" align="center" prop="name" width="260" />
      <el-table-column label="审批意见" align="center" prop="newestMessage" width="380" />
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template #default="scope">
          未审核
        </template>
      </el-table-column>
      <el-table-column label="发起者" align="center" prop="startUserName" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!--
          <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:notice:edit']"
          >修改</el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:notice:remove']"
          >删除</el-button>
          -->
          <el-button
              type="text"
              icon="Edit"
              @click="handleInfo(scope.row)"
          >查看</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改流程对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body destroy-on-close>

      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="申请单" name="first">

          <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
            <el-row align="middle" :gutter="10">
              <el-col :span="8">
                <el-form-item label="入库单号" prop="orderNo">
                  <el-input v-model="form.orderNo" placeholder="请输入入库单号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入库日期" prop="inStoreDate">
                  <el-date-picker clearable v-model="form.inStoreDate" type="date" value-format="YYYY-MM-DD"
                                  style="width: 100%;" placeholder="请选择入库日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属公司" prop="company">
                  <el-tree-select v-model="form.company" :data="deptOptions"
                                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请输入所属公司"
                                  check-strictly style="width:100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row align="middle" :gutter="10">
              <el-col :span="8">
                <el-form-item label="收货单号" prop="supplier">
                  <el-input v-model="form.receiveNo" placeholder="请输入收货单号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="供应商" prop="supplier">
                  <el-select v-model="form.supplier" placeholder="请选择供应商" style="width:100%;">
                    <el-option v-for="supplier in supplierList" :key="supplier.id" :label="supplier.name"
                               :value="supplier.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="来源" prop="source">
                  <el-select v-model="form.source" placeholder="请选择来源" style="width:100%;">
                    <el-option v-for="dict in assets_source" :key="dict.value" :label="dict.label" :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row align="middle" :gutter="10">
              <el-col :span="8">
                <el-form-item label="创建人" prop="createBy">
                  <el-select v-model="form.createBy" placeholder="请输入创建人" style="width:100%;">
                    <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="创建时间" prop="inStoreDate">
                  <el-date-picker clearable v-model="form.inStoreDate" type="date" value-format="YYYY-MM-DD"
                                  style="width: 100%;" placeholder="请选择创建时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入库说明" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入入库说明" />
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>

        </el-tab-pane>
        <el-tab-pane label="流程图" name="second">
          <div class="container" style="position:relative;height:750px;">
            <div class="canvas" ref="canvas"></div>
          </div>
        </el-tab-pane>
      </el-tabs>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Definition">
import { ref, onMounted } from 'vue'
import {getMyProcessTask, getBpmnModelInstance,getHighlightNode} from "@/api/camunda/definition";
// import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/assets/assetsinorder";

import BpmnModeler from 'bpmn-js/lib/Modeler'
import BpmnViewer from "bpmn-js/lib/Viewer"

const activeName = ref('first')
const { proxy } = getCurrentInstance();
const { sys_notice_status, sys_notice_type } = proxy.useDict("sys_notice_status", "sys_notice_type");


const noticeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const department = ref(null);

let exportbtn = ref(null)
let bpmnModeler = ref(null);
let container = ref(null);
let canvas = ref(null);

/*
const viewer = new BpmnJS({
  container: department.value
});
*/

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    noticeTitle: undefined,
    createBy: undefined,
    status: undefined
  },
  rules: {
    noticeTitle: [{ required: true, message: "流程标题不能为空", trigger: "blur" }],
    noticeType: [{ required: true, message: "流程类型不能为空", trigger: "change" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询流程列表 */
function getList() {
  loading.value = true;
  getMyProcessTask(queryParams.value).then(response => {
    noticeList.value = response.data.data;
    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    noticeId: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    noticeContent: undefined,
    status: "0"
  };
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.noticeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加流程";
}
/**修改按钮操作 */
// function handleUpdate(row) {
//   reset();
//   const noticeId = row.noticeId || ids.value;
//   getNotice(noticeId).then(response => {
//     form.value = response.data;
//     open.value = true;
//     title.value = "修改流程";
//   });
// }
/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate(valid => {
    if (valid) {
      if (form.value.noticeId != undefined) {
        updateNotice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addNotice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const noticeIds = row.noticeId || ids.value
  proxy.$modal.confirm('是否确认删除流程编号为"' + noticeIds + '"的数据项？').then(function() {
    return delNotice(noticeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

function handleClick(){

}

onMounted(() => {


})

function handleInfo(row){
  open.value = true;

  //const canvas = department.value
  // 生成实例
  //this.bpmnModeler = new BpmnModeler({
  //  container: canvas
  //})



  getBpmnModelInstance(row.processDefinitionId).then(response=>{
    try {
      //console.log(response.msg);
      // viewer.importXML(response.msg);

      /*
      viewer.importXML(response.msg, function(err) {
        //导入流程图的xml后的结果回调
        console.log("========================");
      });*/
      bpmnModeler = new BpmnViewer({ // 仅预览
        container: canvas.value
      })

      bpmnModeler.importXML(response.msg, (err) => {
        console.log('----------------------------->'+err);
        if (err) {
          console.error(err)
        } else {
          const bpmnCanvas = bpmnModeler.get('canvas')

        }
      });

      /**/
      getHighlightNode(row.processDefinitionId).then(response=>{
        let canvas1 = bpmnModeler.get('canvas');
        console.log("--->"+JSON.stringify(response.data));
        console.log("--->response.data.highLine:"+JSON.stringify(response.data.highLine));

        //高亮线
        response.data.highLine2.forEach((e) => {
          if (e) {
            canvas1.addMarker(e, "highlightFlow");
          }
        });
        //高亮任务
        response.data.highPoint.forEach((e) => {
          if (e) {
            canvas1.addMarker(e, "highlight");
          }
        });
        //高亮我执行过的任务
        response.data.iDo.forEach((e) => {
          if (e) {
            canvas1.addMarker(e, "highlightIDO");
          }
        });
        //高亮下一个任务
        response.data.waitingToDo.forEach((e) => {
          if (e) {
            canvas1.addMarker(e, "highlightTODO");
          }
        });

      });


      console.log('rendered');
    } catch (err) {
      console.log('error rendering', err);
    }
  });

}

getList();
</script>

<style lang="scss">
.container {
  width: 100%;
  height: 100%;

}
//以下几个都是设置的高亮，通过设置类名来控制高亮颜色，此处自定义，可以通过f12开发者工具查看类名来自己定义样式记得样式后面加上!important
//设置高亮点的样式颜色（对应组件参数中的highPoint）
.highlightPoint:not(.djs-connection) .djs-visual> :nth-child(1),
.highlightPoint:not(.djs-connection) .djs-visual>path {
  fill: #ebeaea !important;
  /* color elements as green */
  stroke: #ebeaea !important;
}

//设置高亮线的样式颜色（对应组件参数中的highLine）
.highlightLine {
  .djs-visual {
    path {
      fill: #008000 !important;
      stroke-width: 2px !important;
      stroke: #008000 !important;
      stroke-linejoin: round !important;
      marker-end: url("#sequenceflow-end-green-green-3lfjjpcx65dm9ix6p7cd7oo3y") !important;
    }
  }
}
//设置高亮IDO的样式颜色（对应组件参数中的iDo）
.highlightiDo:not(.djs-connection) .djs-visual> :nth-child(1),
.highlightiDo:not(.djs-connection) .djs-visual>path {
  fill: #a8d894 !important;
  /* color elements as green */
  stroke: #008000 !important;
}
//设置高亮waitingToDo的样式颜色（对应组件参数中的waitingToDo）
.highlightiwaiting:not(.djs-connection) .djs-visual> :nth-child(1),
.highlightiwaiting:not(.djs-connection) .djs-visual>path {
  fill: #ffff0d !important;
  /* color elements as green */
  stroke: #008000 !important;
}

.canvas {
  width: 100%;
  height: 100%;

}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);

  .panel {
    width: 300px;
  }

}


.buttons {
  position: absolute;
  bottom: 0px;

  li {
    /* display: inline-block; */
    margin-right: 10px;
    height: 26px;
    line-height: 26px;
    float: left;
    list-style: none;

    .btn {
      background: #00BCD4;
      border: none;
      outline: none;
      padding: 0px 10px;
      color: #fff;
      display: inline-block;
      opacity: 1;
      height: 26px;
      font-size: 14px;
      line-height: 26px;
    }
  }
}

.highlight .djs-visual > :nth-child(1) {
  stroke: green !important;
  fill: rgba(0, 80, 0, 0.4) !important;
}
.highlightFlow .djs-visual > :nth-child(1) {
  stroke: green !important;
}
.highlightIDO .djs-visual > :nth-child(1) {
  stroke: rgb(255, 196, 0) !important;
  fill: rgba(255, 196, 0, 0.4) !important;
}
.highlightTODO .djs-visual > :nth-child(1) {
  stroke: rgb(255, 0, 0) !important;
  fill: rgba(255, 255, 255, 0.4) !important;
}
</style>
